package odeoncinemaassignment;
import java.awt.print.PrinterJob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;
public class salesReport extends javax.swing.JFrame {
    Connection conn=utilities.connectDB(); // open database connection
    ResultSet rs = null;
    PreparedStatement pst = null;
  
    /** Creates new form salesReport */
    public salesReport() {
        initComponents();
        Date fromDate = salesReportFromDate.getDate();
        Date toDate = salesReportToDate.getDate();
        Date today = new Date(); //to store todays date to set date picker to 
        String dateFormat = "yyyy-MM-dd 23:59:59";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String sql = "select * from sales where dateSold between '"+today+"' and '"+today+"'";
        try{
        pst=conn.prepareStatement(sql);
        rs=pst.executeQuery();
        reportTable.setModel(DbUtils.resultSetToTableModel(rs));
        }
        catch(Exception e){
            JOptionPane.showMessageDialog(null,"An Error Occured "+e);
        }
        salesReportFromDate.setDate(today);
        salesReportToDate.setDate(today); 
        // above sets the report run dates to today by default. 
        // simple date format for database query. 
        salesReport();
        
        
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        titlePanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        getSalesReportButton = new javax.swing.JButton();
        salesReportFromDateLabel = new javax.swing.JLabel();
        salesReportFromDate = new com.toedter.calendar.JDateChooser();
        salesReportToDateLabel = new javax.swing.JLabel();
        salesReportToDate = new com.toedter.calendar.JDateChooser();
        salesReportHeadingPanel = new javax.swing.JPanel();
        salesReportFilmTitle = new javax.swing.JLabel();
        salesReportDateSold = new javax.swing.JLabel();
        salesReportTotalAmount = new javax.swing.JLabel();
        dateSoldSalesReportLabel = new javax.swing.JLabel();
        totalPanel = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        salesReportTotalSales = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        reportTable = new javax.swing.JTable();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel1.setText("Odeon Cinema Sales Report");

        jButton1.setText("Print Report");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        getSalesReportButton.setText("Get Report");
        getSalesReportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getSalesReportButtonActionPerformed(evt);
            }
        });

        salesReportFromDateLabel.setText("From Date:");

        salesReportToDateLabel.setText("To Date:");

        javax.swing.GroupLayout titlePanelLayout = new javax.swing.GroupLayout(titlePanel);
        titlePanel.setLayout(titlePanelLayout);
        titlePanelLayout.setHorizontalGroup(
            titlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, titlePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(138, 138, 138)
                .addComponent(salesReportFromDateLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(salesReportFromDate, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(salesReportToDateLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(salesReportToDate, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(getSalesReportButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );
        titlePanelLayout.setVerticalGroup(
            titlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(titlePanelLayout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(salesReportToDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, titlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1)
                .addComponent(jLabel1)
                .addComponent(getSalesReportButton))
            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, titlePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(salesReportFromDateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(salesReportFromDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(salesReportToDateLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        salesReportFilmTitle.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        salesReportFilmTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        salesReportFilmTitle.setText("Film Title");

        salesReportDateSold.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        salesReportDateSold.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        salesReportDateSold.setText("Number Of Tickets Sold");

        salesReportTotalAmount.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        salesReportTotalAmount.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        salesReportTotalAmount.setText("Total Sale Amount");

        dateSoldSalesReportLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        dateSoldSalesReportLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        dateSoldSalesReportLabel.setText("Date Sold");

        javax.swing.GroupLayout salesReportHeadingPanelLayout = new javax.swing.GroupLayout(salesReportHeadingPanel);
        salesReportHeadingPanel.setLayout(salesReportHeadingPanelLayout);
        salesReportHeadingPanelLayout.setHorizontalGroup(
            salesReportHeadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(salesReportHeadingPanelLayout.createSequentialGroup()
                .addComponent(dateSoldSalesReportLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(salesReportFilmTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(salesReportDateSold, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(salesReportTotalAmount, javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE)
                .addContainerGap())
        );
        salesReportHeadingPanelLayout.setVerticalGroup(
            salesReportHeadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(salesReportHeadingPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(dateSoldSalesReportLabel)
                .addComponent(salesReportFilmTitle)
                .addComponent(salesReportDateSold)
                .addComponent(salesReportTotalAmount))
        );

        jLabel2.setText("Total Sales: ");

        salesReportTotalSales.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        salesReportTotalSales.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        salesReportTotalSales.setText("amount here");
        double runTot = retailFrame.runningTotal;
        String a = Double.toString(runTot);
        salesReport.salesReportTotalSales.setText("€"+a);

        javax.swing.GroupLayout totalPanelLayout = new javax.swing.GroupLayout(totalPanel);
        totalPanel.setLayout(totalPanelLayout);
        totalPanelLayout.setHorizontalGroup(
            totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, totalPanelLayout.createSequentialGroup()
                .addContainerGap(784, Short.MAX_VALUE)
                .addComponent(jLabel2)
                .addGap(62, 62, 62)
                .addComponent(salesReportTotalSales, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        totalPanelLayout.setVerticalGroup(
            totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(totalPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(totalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(salesReportTotalSales))
                .addContainerGap(31, Short.MAX_VALUE))
        );

        reportTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(reportTable);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 617, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(totalPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(titlePanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(salesReportHeadingPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(titlePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22)
                .addComponent(salesReportHeadingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(totalPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        utilities.exitToMenu();
    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        utilities.exitToMenu();
    }//GEN-LAST:event_formWindowClosing

    private void getSalesReportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getSalesReportButtonActionPerformed
salesReport();
        
        
        //        String dateFormat = "yyyy-MM-dd 23:59:59";
//        String dateFormat2 = "yyyy-MM-dd 00:00:00";
//        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//        SimpleDateFormat sdf1 = new SimpleDateFormat(dateFormat2); //want to search from today at 00:00:00 not 23:59:59
//        Date fromDate = salesReportFromDate.getDate();
//        Date toDate = salesReportToDate.getDate();
//        try{
//        String sql = "select saleId as 'ID',  from sales where dateSold between '"+sdf1.format(fromDate)+"' and '"+sdf.format(toDate)+"'";
//        System.out.print("searching from time"+sdf.format(fromDate));
//        System.out.print("searching from time"+sdf.format(toDate));
//        pst=conn.prepareStatement(sql);
//        rs=pst.executeQuery();
//        reportTable.setModel(DbUtils.resultSetToTableModel(rs));
//        double total=0;
//        Object o;
//        for(int i=0; i<reportTable.getRowCount();i++){
//        o=reportTable.getValueAt(i, 3); // get value stored in the totalPrice column
//        total+=Double.parseDouble(o.toString());         // parse to double and store in 'total'
//        //JOptionPane.showMessageDialog(null, "Total is now: "+total);     //check its working ok    
//                
//                }
//        String strTotal = utilities.df.format(total);
//        // format to 2 decimal places
//        salesReportTotalSales.setText("€ "+strTotal );
//        // print to label
//    }
//        
//    catch(Exception e){
//        JOptionPane.showMessageDialog(null,"An Error Occured "+e);
//    }
        
        
//        SimpleDateFormat sdf = new SimpleDateFormat();
//    
//    Date fromDate=salesReportFromDate.getDate();                                        //date from which to run report. value taken from date picker. Cannot be a date after the to date.
//    String strFromDate = fromDate.toString();
//    String calenderToDate;                  //Date to run report to. from date MUST be specified otherwise it defaults to todays date.
//    String format="yyyy-mm-dd hh:mm:ss";    // format for date so it gets correct date from database.
//    String strDate ;                        // string representation of date here 
//    //String dbString = "select * from sales where date is between "+calenderFromDate+"and "+calenderToDate; //sql to excecute once getReport is involked
//    JOptionPane.showMessageDialog(null,"The date chosen was: "+strFromDate);
    }//GEN-LAST:event_getSalesReportButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        PrinterJob.getPrinterJob();
        PrinterJob.lookupPrintServices();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(salesReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(salesReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(salesReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(salesReport.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//
//            public void run() {
//                new salesReport().setVisible(true);
//            }
//        });
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel dateSoldSalesReportLabel;
    private javax.swing.JButton getSalesReportButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable reportTable;
    private javax.swing.JLabel salesReportDateSold;
    private javax.swing.JLabel salesReportFilmTitle;
    private com.toedter.calendar.JDateChooser salesReportFromDate;
    private javax.swing.JLabel salesReportFromDateLabel;
    private javax.swing.JPanel salesReportHeadingPanel;
    private com.toedter.calendar.JDateChooser salesReportToDate;
    private javax.swing.JLabel salesReportToDateLabel;
    private javax.swing.JLabel salesReportTotalAmount;
    public static javax.swing.JLabel salesReportTotalSales;
    private javax.swing.JPanel titlePanel;
    private javax.swing.JPanel totalPanel;
    // End of variables declaration//GEN-END:variables

public void getSalesFromDB(){
    // method fetches sales data from database. uses specific date period which must be selected when getReport is involked
    // it updates the report in real time with the most current data and prints the report to screen
        
   // check date so it conforms to rules:
   // look up performing mathematical functions on dates 
    
    if(checkDate()==true){
        JOptionPane.showMessageDialog(null,"Select a date no later than the 'to' Date!","ERRROR!",JOptionPane.ERROR_MESSAGE);
    }
    

    
}

    boolean checkDate(){
    // method to compare two dates and return true if date one is after date two
    
    return true;
}
    
    public void salesReport(){
        String dateFormat = "yyyy-MM-dd 23:59:59";
        String dateFormat2 = "yyyy-MM-dd 00:00:00";
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        SimpleDateFormat sdf1 = new SimpleDateFormat(dateFormat2); //want to search from today at 00:00:00 not 23:59:59
        Date fromDate = salesReportFromDate.getDate();
        Date toDate = salesReportToDate.getDate();
        try{
        String sql = "select *  from sales where dateSold between '"+sdf1.format(fromDate)+"' and '"+sdf.format(toDate)+"'";
        System.out.print("searching from time"+sdf.format(fromDate));
        System.out.print("searching from time"+sdf.format(toDate));
        pst=conn.prepareStatement(sql);
        rs=pst.executeQuery();
        reportTable.setModel(DbUtils.resultSetToTableModel(rs));
        double total=0;
        Object o;
        for(int i=0; i<reportTable.getRowCount();i++){
        o=reportTable.getValueAt(i, 3); // get value stored in the totalPrice column
        total+=Double.parseDouble(o.toString());         // parse to double and store in 'total'
        //JOptionPane.showMessageDialog(null, "Total is now: "+total);     //check its working ok    
                
                }
        String strTotal = utilities.df.format(total);
        // format to 2 decimal places
        salesReportTotalSales.setText("€ "+strTotal );
        // print to label
    }
        
    catch(Exception e){
        JOptionPane.showMessageDialog(null,"An Error Occured "+e);
    }
        
    }


}
